import React, { useEffect, useState } from "react";
import { Space, Checkbox, Popconfirm, Button, message, Empty } from "antd";
import RenderGoods from "./RenderGoods";
import useEventListener from "@/hooks/useEventListener";
import AddCombinaGoods from "@/components/AddCombinaGoods";
import BatchAddCombine from "./BatchAddCombine";
import FooterToolbar from "@/components/FooterToolbar";
import CommonPage from "@/components/CommonPagination";
import CommonLoading from "@/components/CommonLoading";
import EditChannel from "./EditChannel";
import { pull, cloneDeep } from "lodash";
import { deleteGoods, getGoodsList } from "../service";
import { EditOutlined } from "@ant-design/icons";
import { handleSetHeight } from "@/utils/utils.jsx";
import styles from "./GoodsList.module.less";

export default ({ query, divEl, tableKey, handleOk }) => {
	//组合商品列表
	const [goodsList, setGoodsList] = useState([]);

	//控制修改渠道弹框
	const [visible, setVisible] = useState(false);

	//当前修改的渠道
	const [item, setItem] = useState({});

	const [loading, setLoading] = useState(false);

	//选中操作的商品
	const [selectGoods, setSelectGoods] = useState([]);

	//控制组合商品弹框
	const [modalInfo, setModalInfo] = useState({
		visible: false,
		title: "新增组合商品",
		item: {}
	});

	//批量新增组合
	const [batchVisible, setBatchVisible] = useState(false);

	//分页数据
	const [pages, setPages] = useState({
		total: 0,
		current: 1,
		pageSize: 10,
		pageSizeOptions: [10, 20]
	});

	//表格滚动高度
	const [scrollHeight, setScrollHeight] = useState(600);

	//初始执行一下计算高度的函数
	useEffect(() => {
		setScrollHeight(handleSetHeight(divEl, 0, 128));
	}, []);

	//监听窗口尺寸变化计算一下高度
	useEventListener(window, "resize", () => {
		setScrollHeight(handleSetHeight(divEl, 0, 128));
	});

	//数据发生变化后重置选中数据
	useEffect(() => {
		setSelectGoods([]);
		setPages({ ...pages, current: 1 });
		queryGoodsList(query, { ...pages, current: 1 });
	}, [tableKey]);

	//获取组合商品列表
	const queryGoodsList = async (query, page) => {
		setLoading(true);
		setGoodsList([]);
		// 查询条件收尾去空格
		const params = {
			composeName: query.composeName,
			code: query.code, //组合编号
			zjfGoodsState: query.zjfGoodsState, //是否上下价
			current: page.current,
			size: page.pageSize
		};
		const { success, data } = await getGoodsList(params);
		if (success) {
			const { records, total } = data;
			setGoodsList(records);
			setPages({ ...page, total });
			setLoading(false);
		} else {
			setLoading(false);
		}
	};

	//批量删除
	const handleDeleteAll = () => {
		if (selectGoods.length > 0) {
			const str = selectGoods.join(",");
			handleDelete(str);
		} else {
			message.warning("请选择要操作的商品");
		}
	};

	//新增组合商品
	const handleAdd = () => {
		setModalInfo({
			visible: true,
			title: "单个新增组合商品",
			item: {}
		});
	};

	//点击全选按钮
	const handleCheckAll = e => {
		const val = e.target.checked;
		if (val) {
			const arr = [];
			for (let i in goodsList) {
				arr.push(goodsList[i].id);
			}
			setSelectGoods(arr);
		} else {
			setSelectGoods([]);
		}
	};

	//点击选择单个商品
	const handleChange = (e, id) => {
		const val = e.target.checked;
		const arr = cloneDeep(selectGoods);
		if (val) {
			arr.push(id);
		} else {
			pull(arr, id);
		}
		setSelectGoods(arr);
	};

	//复制商品
	const handleCopy = val => {
		const obj = cloneDeep(val);
		obj.id = undefined;
		setModalInfo({
			visible: true,
			title: "单个新增组合商品",
			item: obj
		});
	};

	//编辑商品
	const handleEdit = async val => {
		const obj = cloneDeep(val);
		setModalInfo({
			visible: true,
			title: "单个编辑组合商品",
			item: obj
		});
		// handleLoading(true);
		// const { success, data } = await getCommonOrderUse({
		//   commonId: val.id,
		// })
		// handleLoading(false);
		// if(success) {
		//   if(data > 0) {
		//     Modal.confirm({
		// className: "views-modal-confirm",
		// centered: true,
		//       title: '确认信息',
		//       icon: <Iconfont type="iconjingshi" />,
		//       content: '该组合商品已有订单匹配，确定需要修改吗?',
		//       onOk() {
		//         const obj = cloneDeep(val);
		//         setModalInfo({
		//           visible: true,
		//           title: '编辑组合商品',
		//           item: obj,
		//         })
		//       },
		//     });
		//   } else {

		//   }
		// }
	};

	//删除组合商品
	const handleDelete = async id => {
		setLoading(true);
		const { success } = await deleteGoods({
			ids: id
		});
		setLoading(false);
		if (success) {
			message.success("删除成功！");
			queryGoodsList(query, pages);
			handleOk();
		}
	};

	//修改渠道
	const handleEditChannel = v => {
		setItem(v);
		setVisible(true);
	};

	//添加组合商品弹框
	const AddCombinaGoodsProps = {
		modalInfo,
		handleCancel() {
			const obj = { ...modalInfo };
			obj.visible = false;
			obj.item = {};
			setModalInfo(obj);
		},
		handleOk() {
			const obj = { ...modalInfo };
			obj.visible = false;
			obj.item = {};
			setModalInfo(obj);
			queryGoodsList(query, pages);
			handleOk();
		}
	};

	//批量添加组合商品弹框
	const BatchAddCombinaGoodsProps = {
		visible: batchVisible,
		handleCancel() {
			setBatchVisible(false);
		},
		handleOk() {
			setBatchVisible(false);
			queryGoodsList(query, pages);
		}
	};

	//修改渠道
	const EditChannelProps = {
		visible,
		item,
		handleOk() {
			setVisible(false);
			queryGoodsList(query, pages);
		},
		handleCancel() {
			setVisible(false);
		}
	};

	//分页props
	const PageProps = {
		pagination: pages,
		handleChange(current, size) {
			const obj = { ...pages, current, pageSize: size };
			setPages(obj);
			queryGoodsList(query, obj);
		}
	};

	return (
		<>
			<div style={{ paddingLeft: "12px", marginBottom: "12px" }}>
				<Space>
					<span>全选</span>
					<Checkbox
						indeterminate={selectGoods.length > 0 && selectGoods.length < goodsList.length}
						checked={goodsList.length ? (selectGoods.length == goodsList.length ? true : false) : false}
						disabled={goodsList.length ? false : true}
						onChange={handleCheckAll}
						className="allCheckedStyle"
					/>
					<Button disabled={goodsList.length > 0 ? false : true} onClick={handleDeleteAll}>
						批量删除
					</Button>
					<Button onClick={() => handleAdd(true)} style={{ margin: "0 8px" }}>
						单个新增组合
					</Button>
					<Button onClick={() => setBatchVisible(true)}>批量新增组合</Button>
				</Space>
			</div>
			<div className={styles.section} style={{ maxHeight: scrollHeight }}>
				{goodsList.length > 0 ? (
					goodsList.map((v, index) => {
						const { composeGoodsDetails = [], composeName, id, channelName, code } = v;
						return (
							<div key={index}>
								<div className={styles.titleBar}>
									<div style={{ display: "flex", alignItems: "baseline", paddingLeft: "8px" }}>
										<Checkbox onChange={e => handleChange(e, id)} checked={selectGoods.includes(id) ? true : false} />
										<div style={{ margin: "4px 12px" }}>
											<span>组合商品名称: {composeName}</span>
											<span style={{ marginLeft: "12px" }}>组合编号: {code}</span>
										</div>
										<div style={{ margin: "4px 12px" }}>
											<span>发货渠道: {channelName}</span>
											<EditOutlined
												className="common-color2"
												onClick={() => handleEditChannel(v)}
												style={{ cursor: "pointer", fontSize: "14px", marginLeft: "8px" }}
											/>
										</div>
									</div>
									<div>
										<Space style={{ width: "120px" }}>
											<span onClick={() => handleCopy(goodsList[index])} className="common-color2">
												复制
											</span>
											<span onClick={() => handleEdit(goodsList[index])} className="common-color2">
												编辑
											</span>
											<Popconfirm
												title="确定要删除吗?"
												onConfirm={() => handleDelete(id)}
												okText="确定"
												placement="topRight"
												cancelText="取消"
											>
												<span className="common-color2">删除</span>
											</Popconfirm>
										</Space>
									</div>
								</div>
								<div className={styles.goodsWrap}>
									{composeGoodsDetails.length > 0 ? (
										composeGoodsDetails.map((v, index) => <RenderGoods key={index} item={v} />)
									) : (
										<div style={{ textAlign: "center", width: "100%" }}>
											<Empty description="暂无商品信息" />
										</div>
									)}
								</div>
							</div>
						);
					})
				) : (
					<Empty />
				)}
			</div>
			{modalInfo.visible && <AddCombinaGoods {...AddCombinaGoodsProps} />}
			{batchVisible && <BatchAddCombine {...BatchAddCombinaGoodsProps} />}
			{visible && <EditChannel {...EditChannelProps} />}
			<FooterToolbar>
				<CommonPage {...PageProps} />
			</FooterToolbar>
			<CommonLoading loading={loading} />
		</>
	);
};
